package com.bjb.vr.operation.utils;

import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取请求信息工具类
 *
 * @description:
 * @author: HuJingBo
 * @time: 2022/5/18 19:15
 */
public class AccessRequestUtil {

    /**
     * 获取请求地址
     * @return
     */
    public static String getRequestURI(){
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request.getRequestURI();
    }

    /**
     * 获取请求头参数
     *
     * @return
     */
    public static Map<String, String> takeHeaders() {
        Map<String, String> requestParams = new HashMap<>();
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取请求头信息(需要注意的是:请求头中的key都会转成小写)
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            requestParams.put(name, value);
        }
        return requestParams;
    }

    /**
     * 获取请求的用户名信息
     *
     * @return
     */
    public static String getUserName() {
        Map<String, String> headers = takeHeaders();
        Claims claims = JwtTokenUtil.parseJWT(headers.get(TokenConstants.AUTHORIZATION.toLowerCase()));
        String username = String.valueOf(claims.get(TokenConstants.TOKEN_USERNAME));
        return username;
    }

    /**
     * 获取请求的租户信息
     *
     * @return
     */
    public static String getTenantId() {
        Map<String, String> headers = takeHeaders();
        Claims claims = JwtTokenUtil.parseJWT(headers.get(TokenConstants.AUTHORIZATION.toLowerCase()));
        String tenantId = String.valueOf(claims.get(TokenConstants.TENANT_ID));
        return tenantId;
    }
}
